﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;

namespace RL
{
    /// <summary>
    /// Логика взаимодействия для wStationMoney.xaml
    /// </summary>
    public partial class wStationMoney : Window
    {


        public routelistEntities ContextDB
        {
            get { return (routelistEntities)GetValue(ContextDBProperty); }
            set { SetValue(ContextDBProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ContextDB.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ContextDBProperty =
            DependencyProperty.Register("ContextDB", typeof(routelistEntities), typeof(wStationMoney), new UIPropertyMetadata(null, propContextDB));

        public static void propContextDB(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            wStationMoney item = d as wStationMoney;
            if (null == item) return;
            routelistEntities it = e.NewValue as routelistEntities;
            if (null == it) return;
            //item.ContextDB = it;
        }

        

        public wStationMoney()
        {
            InitializeComponent();
        }

        private void buttonAdd_Click(object sender, RoutedEventArgs e)
        {
            if (null == ContextDB) return;
            try
            {
                System.Windows.Data.CollectionViewSource vokzalTableViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vokzalTableViewSource")));
                IEditableCollectionView vw = vokzalTableViewSource.View as IEditableCollectionView;
                if (null == vw) return;
                RouteList rl = null;
                wRouteList wnd = new wRouteList();
                wnd.ContextDB = ContextDB;
                if (wnd.ShowDialog() == false)
                {
                    return;
                }
                rl = wnd.RouteList;
                if (null == rl) return;
                RouteListSchedule sch = (from o in rl.RouteListSchedule where o.time_departure.Trim() != "" orderby o.time_departure select o).FirstOrDefault();
                Routes sel_rt;
                if (null == sch)
                {
                    MessageBox.Show("В выбранном путевом листе нет информации о расписании. Выберите маршрут.");
                    wRouteRegistry ws = new wRouteRegistry();
                    ws.ContextDB = ContextDB;
                    if (false == ws.ShowDialog())
                        return;
                    sel_rt = ws.Route;
                    if (null == sel_rt) return;


                }
                else
                {
                    sel_rt = sch.Routes;
                }
                if (null == sel_rt) return;
                VokzalTable item = vw.AddNew() as VokzalTable;
                if (null == item) return;
                App curApp = (App)App.Current;
                item.datedoc = curApp.WorkDate;
                item.numdoc = "";
                item.RouteList = rl;
                item.Routes = sel_rt;
                item.time_departure = null == sch ? "" : sch.time_departure;
                item.qnt_tickets = 0;
                item.qnt_lgot_ticket = 0;
                item.qnt_child_ticket = 0;
                item.summa_tickets = 0;
                item.summ_lgot_ticket = 0;
                item.summ_child_ticket = 0;
                item.summ_free_ticket = 0;
                item.del = false;
                vw.CommitNew();
                SaveData();
                vokzalTableViewSource.View.MoveCurrentTo(item);
                vokzalTableDataGrid.ScrollIntoView(item);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void buttonDelete_Click(object sender, RoutedEventArgs e)
        {
            if (ContextDB == null) return;
            System.Windows.Data.CollectionViewSource vokzalTableViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vokzalTableViewSource")));
            VokzalTable item = vokzalTableViewSource.View.CurrentItem as VokzalTable;
            if (null == item) return;
            ContextDB.DeleteObject(item);
        }

        private void buttonEdit_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Data.CollectionViewSource vokzalTableViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vokzalTableViewSource")));
            VokzalTable item = vokzalTableViewSource.View.CurrentItem as VokzalTable;
            if (null == item) return;
            wStationMoneyTable wnd = new wStationMoneyTable();
            wnd.VokzalTableID = item.id;
            //wnd.ContextDB = ContextDB;
            //wnd.VokzalTable = item;
            if (true == wnd.ShowDialog())
            {
                //vokzalTableViewSource.View.Refresh();
                ContextDB.Refresh(System.Data.Objects.RefreshMode.StoreWins, item);
                //vokzalTableViewSource.View.Refresh();
            }
        }

        private System.Data.Objects.ObjectQuery<VokzalTable> GetVokzalTableQuery(routelistEntities routelistEntities)
        {
            // Автоматически созданный код

            System.Data.Objects.ObjectQuery<RL.VokzalTable> vokzalTableQuery = routelistEntities.VokzalTable.Include("RouteList").Include("Routes");
            // Для явной загрузки данных, возможно, потребуется добавить методы Include, аналогичные показанным ниже:
            // vokzalTableQuery = vokzalTableQuery.Include("VokzalTable.RouteList").
            // Дополнительные сведения см. по ссылке http://go.microsoft.com/fwlink/?LinkId=157380
            // Возвращает ObjectQuery.
            return vokzalTableQuery;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            RL.routelistEntities routelistEntities;
            if (null != ContextDB)
            {
                routelistEntities = ContextDB;
            }
            else
            {
                routelistEntities = new RL.routelistEntities();
                ContextDB = routelistEntities;
            }
            // Загрузить данные в VokzalTable. Можно изменить этот код как требуется.
            System.Windows.Data.CollectionViewSource vokzalTableViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("vokzalTableViewSource")));
            System.Data.Objects.ObjectQuery<RL.VokzalTable> vokzalTableQuery = this.GetVokzalTableQuery(routelistEntities);
            vokzalTableViewSource.Source = from o in routelistEntities.VokzalTable orderby o.datedoc, o.RouteList.nomdog select o;//vokzalTableQuery.Execute(System.Data.Objects.MergeOption.AppendOnly);
            //vokzalTableDataGrid.Items.SortDescriptions.Add(new SortDescription("datedoc", ListSortDirection.Ascending));
            //vokzalTableDataGrid.Items.SortDescriptions.Add(new SortDescription("RouteList.nomdog", ListSortDirection.Ascending));
        }

        private bool IsModified()
        {
            bool bResult = false;
            if (null == ContextDB) return false;
            bResult = ContextDB.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added).Count() > 0 || ContextDB.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Deleted).Count() > 0 || ContextDB.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified).Count() > 0;
            return bResult;
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (IsModified())
            {
                var result = MessageBox.Show("Сохранить изменения?", "Предупреждение", MessageBoxButton.YesNoCancel, MessageBoxImage.Exclamation, MessageBoxResult.Yes);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        if (false == SaveData())
                        {
                            e.Cancel = true;
                        }
                        break;
                    case MessageBoxResult.Cancel:
                        e.Cancel = true;
                        break;
                }

            }
        }

        private bool SaveData()
        {
            bool bResult = true;
            try
            {
                ContextDB.SaveChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), Properties.Resources.DataSavingError, MessageBoxButton.OK, MessageBoxImage.Exclamation);
                bResult = false;
            }
            return bResult;
        }

        private void buttonSave_Click(object sender, RoutedEventArgs e)
        {
            SaveData();
        }

    }
}
